const jwt = require('jsonwebtoken');

const JWT_SECRET = 'h5_secret';  // H5专用密钥，建议放在环境变量中

// H5白名单路由
const h5WhiteList = [
  '/api/h5/auth/login',
  '/api/h5/auth/register',
  '/api/h5/dict/list',
  '/api/h5/products/list',
  '/api/h5/categories/list',
  '/api/h5/brands/list',
];

const h5AuthMiddleware = (req, res, next) => {
  // 如果是白名单路由，直接通过
  const fullPath = `/api${req.path}`;
  if (h5WhiteList.includes(fullPath)) {
    return next();
  }

  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({
      code:401,
      message: '未登录或登录已过期33'
    });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).json({
      code:401,
      message: '未登录或登录已过期44'
    });
  }
};

module.exports = h5AuthMiddleware; 